﻿using System;
using System.Collections.Generic;
using System.Text;

namespace SharpSoft
{
    /// <summary>
    /// 可以提供一组异步状态对象
    /// </summary>
    /// <typeparam name="T">键的类型</typeparam>
    /// <remarks>此类型的所有实例方法本身都是线程安全的</remarks>
    public class AsyncState<T>
    {
        private Dictionary<T, object> dic = new Dictionary<T, object>();
        private readonly object asyncState = new object();//此实例本身的异步状态对象
        public AsyncState()
        {

        }
        /// <summary>
        /// 获取键对应的状态对象
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public object this[T index]
        {
            get
            {
                lock (this.asyncState)
                {
                    if (dic.ContainsKey(index))
                    {
                        return dic[index];
                    }
                    else
                    {
                        object state = new object();
                        dic.Add(index, state);
                        return state;
                    }
                }

            }
        }
        /// <summary>
        /// 移除短期内无需再使用的状态对象
        /// </summary>
        /// <param name="key"></param>
        public void RemoveState(T key)
        {
            lock (this.asyncState)
            {
                if (dic.ContainsKey(key))
                {
                    dic.Remove(key);
                }
            }
        }
    }
}
